import React, { createContext, useContext, useReducer, ReactNode } from 'react';
import { Task, News, User } from '../types';

// 定义状态类型
interface AppState {
  tasks: Task[];
  news: News[];
  user: User;
  currentTask: string;
  editingTaskId: string | null;
  refreshing: boolean;
  darkMode: boolean;
  syncEnabled: boolean;
  autoBackup: boolean;
}

// 定义Action类型
type AppAction =
  | { type: 'SET_TASKS'; payload: Task[] }
  | { type: 'ADD_TASK'; payload: Task }
  | { type: 'UPDATE_TASK'; payload: { id: string; task: Partial<Task> } }
  | { type: 'DELETE_TASK'; payload: string }
  | { type: 'TOGGLE_TASK'; payload: string }
  | { type: 'SET_NEWS'; payload: News[] }
  | { type: 'ADD_NEWS'; payload: News }
  | { type: 'SET_CURRENT_TASK'; payload: string }
  | { type: 'SET_EDITING_TASK_ID'; payload: string | null }
  | { type: 'SET_REFRESHING'; payload: boolean }
  | { type: 'SET_USER'; payload: User }
  | { type: 'SET_DARK_MODE'; payload: boolean }
  | { type: 'TOGGLE_DARK_MODE' }
  | { type: 'TOGGLE_SYNC'; payload: boolean }
  | { type: 'TOGGLE_AUTO_BACKUP'; payload: boolean };

// 初始状态
const initialState: AppState = {
  tasks: [
    {
      id: '1',
      title: '完成React Native项目重构',
      completed: false,
      createdAt: '2024-01-15 10:30',
    },
    {
      id: '2',
      title: '学习TypeScript高级特性',
      completed: true,
      createdAt: '2024-01-14 09:15',
    },
  ],
  news: [
    {
      id: '1',
      title: 'React Native 0.80 版本发布',
      content: 'React Native 最新版本带来了许多性能改进和新功能，包括更好的TypeScript支持...',
      publishTime: '2024-01-15 14:30',
    },
    {
      id: '2',
      title: 'TypeScript 5.0 正式发布',
      content: 'TypeScript 5.0 版本包含了装饰器支持和性能优化，为开发者带来更好的体验...',
      publishTime: '2024-01-14 16:45',
    },
  ],
  user: {
    id: '1',
    name: '张三',
    email: 'zhangsan@example.com',
    avatar: '👤',
  },
  currentTask: '',
  editingTaskId: null,
  refreshing: false,
  darkMode: false,
  syncEnabled: false,
  autoBackup: true,
};

// Reducer函数
const appReducer = (state: AppState, action: AppAction): AppState => {
  switch (action.type) {
    case 'SET_TASKS':
      return { ...state, tasks: action.payload };
    case 'ADD_TASK':
      return { ...state, tasks: [action.payload, ...state.tasks] };
    case 'UPDATE_TASK':
      return {
        ...state,
        tasks: state.tasks.map(task =>
          task.id === action.payload.id
            ? { ...task, ...action.payload.task }
            : task
        ),
      };
    case 'DELETE_TASK':
      return {
        ...state,
        tasks: state.tasks.filter(task => task.id !== action.payload),
      };
    case 'TOGGLE_TASK':
      return {
        ...state,
        tasks: state.tasks.map(task =>
          task.id === action.payload
            ? { ...task, completed: !task.completed }
            : task
        ),
      };
    case 'SET_NEWS':
      return { ...state, news: action.payload };
    case 'ADD_NEWS':
      return { ...state, news: [action.payload, ...state.news] };
    case 'SET_CURRENT_TASK':
      return { ...state, currentTask: action.payload };
    case 'SET_EDITING_TASK_ID':
      return { ...state, editingTaskId: action.payload };
    case 'SET_REFRESHING':
      return { ...state, refreshing: action.payload };
    case 'SET_USER':
      return { ...state, user: action.payload };
    case 'SET_DARK_MODE':
      return { ...state, darkMode: action.payload };
    case 'TOGGLE_DARK_MODE':
      return { ...state, darkMode: !state.darkMode };
    case 'TOGGLE_SYNC':
      return { ...state, syncEnabled: action.payload };
    case 'TOGGLE_AUTO_BACKUP':
      return { ...state, autoBackup: action.payload };
    default:
      return state;
  }
};

// Context类型
interface AppContextType {
  state: AppState;
  dispatch: React.Dispatch<AppAction>;
  // 便捷方法
  addTask: (title: string) => void;
  updateTask: (id: string, title: string) => void;
  deleteTask: (id: string) => void;
  toggleTask: (id: string) => void;
  setCurrentTask: (task: string) => void;
  setEditingTaskId: (id: string | null) => void;
  addNews: (news: News) => void;
  setRefreshing: (refreshing: boolean) => void;
  setDarkMode: (darkMode: boolean) => void;
  toggleDarkMode: () => void;
}

// 创建Context
const AppContext = createContext<AppContextType | undefined>(undefined);

// Provider组件
interface AppProviderProps {
  children: ReactNode;
}

export const AppProvider: React.FC<AppProviderProps> = ({ children }) => {
  const [state, dispatch] = useReducer(appReducer, initialState);

  // 便捷方法
  const addTask = (title: string) => {
    const newTask: Task = {
      id: Date.now().toString(),
      title,
      completed: false,
      createdAt: new Date().toLocaleString(),
    };
    dispatch({ type: 'ADD_TASK', payload: newTask });
  };

  const updateTask = (id: string, title: string) => {
    dispatch({ type: 'UPDATE_TASK', payload: { id, task: { title } } });
  };

  const deleteTask = (id: string) => {
    dispatch({ type: 'DELETE_TASK', payload: id });
  };

  const toggleTask = (id: string) => {
    dispatch({ type: 'TOGGLE_TASK', payload: id });
  };

  const setCurrentTask = (task: string) => {
    dispatch({ type: 'SET_CURRENT_TASK', payload: task });
  };

  const setEditingTaskId = (id: string | null) => {
    dispatch({ type: 'SET_EDITING_TASK_ID', payload: id });
  };

  const addNews = (news: News) => {
    dispatch({ type: 'ADD_NEWS', payload: news });
  };

  const setRefreshing = (refreshing: boolean) => {
    dispatch({ type: 'SET_REFRESHING', payload: refreshing });
  };

  const setDarkMode = (darkMode: boolean) => {
    dispatch({ type: 'SET_DARK_MODE', payload: darkMode });
  };

  const toggleDarkMode = () => {
    dispatch({ type: 'TOGGLE_DARK_MODE' });
  };

  const value: AppContextType = {
    state,
    dispatch,
    addTask,
    updateTask,
    deleteTask,
    toggleTask,
    setCurrentTask,
    setEditingTaskId,
    addNews,
    setRefreshing,
    setDarkMode,
    toggleDarkMode,
  };

  return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
};

// 自定义Hook
export const useAppContext = (): AppContextType => {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useAppContext must be used within an AppProvider');
  }
  return context;
};